package isstra.gestore;
import java.util.*;
public class GestoreMJFifo implements Gestore{
	private LinkedList<Thread> arrivi=new LinkedList<Thread>();
	private boolean release=false;
	private int cnt=0;
	private Object lock=new Object();
	private boolean processoDeveDormire(){
		if( release || Thread.currentThread()!=arrivi.getFirst() )
			return true;
		return false;
	}
	public void request(){
		synchronized(lock){
			arrivi.addLast( Thread.currentThread() );
			while( processoDeveDormire() ){
				try{ lock.wait(); }catch(InterruptedException e){}
			}
			arrivi.removeFirst();
			cnt++;
			if( cnt==3 ) release=true;
			lock.notifyAll();
			System.out.println(Thread.currentThread().getName()+" entra");
		}
	}//request
	public void finish(){
		synchronized(lock){
			cnt--;
			if( cnt==0 ){
				release=false;
				lock.notifyAll();
			}
			System.out.println(Thread.currentThread().getName()+" esce");
		}
	}//finish
}//GestoreMJFifo
